package com.blog.cmrpersonalblog.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.blog.cmrpersonalblog.common.Result;
import com.blog.cmrpersonalblog.dto.article.request.UserArticleQueryRequest;
import com.blog.cmrpersonalblog.dto.user.response.AdminUserProfileResponse;
import com.blog.cmrpersonalblog.dto.user.response.UserInteractionResponse;
import com.blog.cmrpersonalblog.dto.user.response.UserProfileResponse;
import com.blog.cmrpersonalblog.service.UserProfileService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 后台管理用户详情控制器
 */
@Slf4j
@RestController
@RequestMapping("/admin/user-profile")
@CrossOrigin(origins = "*", maxAge = 3600)
public class AdminUserProfileController {

   @Resource
    private UserProfileService userProfileService;

   @Resource
    private HttpServletRequest request;

    /**
     * 获取后台管理用户详情信息
     */
    @GetMapping("/{userId}")
    @SaCheckRole("admin")
    public Result<AdminUserProfileResponse> getAdminUserProfile(@PathVariable Long userId) {
        try {
            log.info("管理员查看用户详情: userId={}, adminId={}", userId, StpUtil.getLoginIdAsString());
            
            AdminUserProfileResponse profile = userProfileService.getAdminUserProfile(userId);
            if (profile == null) {
                return Result.error("用户不存在");
            }
            
            // 记录管理员查看用户详情的操作
            recordAdminActivity("VIEW_USER_PROFILE", "查看用户详情", userId, "user");
            
            return Result.success(profile);
        } catch (Exception e) {
            log.error("获取后台用户详情失败", e);
            return Result.error("获取用户详情失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询用户发布的文章（后台管理）
     */
    @GetMapping("/{userId}/articles")
    @SaCheckRole("admin")
    public Result<IPage<UserProfileResponse.ArticleInfo>> getAdminUserArticles(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) String tagName,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "publish_time") String orderBy,
            @RequestParam(defaultValue = "desc") String orderDirection) {
        try {
            log.info("管理员查看用户文章: userId={}, adminId={}", userId, StpUtil.getLoginIdAsString());
            
            UserArticleQueryRequest query = new UserArticleQueryRequest();
            query.setUserId(userId);
            query.setPage(page);
            query.setSize(size);
            query.setStatus(status);
            query.setCategoryId(categoryId);
            query.setTagName(tagName);
            query.setKeyword(keyword);
            query.setOrderBy(orderBy);
            query.setOrderDirection(orderDirection);
            
            IPage<UserProfileResponse.ArticleInfo> articles = userProfileService.getUserArticles(query);
            
            // 记录管理员查看用户文章的操作
            recordAdminActivity("VIEW_USER_ARTICLES", "查看用户文章列表", userId, "user");
            
            return Result.success(articles);
        } catch (Exception e) {
            log.error("查询用户文章失败", e);
            return Result.error("查询用户文章失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户互动数据（后台管理）
     */
    @GetMapping("/{userId}/interactions")
    @SaCheckRole("admin")
    public Result<UserInteractionResponse> getAdminUserInteractions(@PathVariable Long userId) {
        try {
            log.info("管理员查看用户互动数据: userId={}, adminId={}", userId, StpUtil.getLoginIdAsString());
            
            UserInteractionResponse interactions = userProfileService.getUserInteractions(userId, null);
            
            // 记录管理员查看用户互动数据的操作
            recordAdminActivity("VIEW_USER_INTERACTIONS", "查看用户互动数据", userId, "user");
            
            return Result.success(interactions);
        } catch (Exception e) {
            log.error("获取用户互动数据失败", e);
            return Result.error("获取用户互动数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户内容发布统计信息
     */
    @GetMapping("/{userId}/content-stats")
    @SaCheckRole("admin")
    public Result<AdminUserProfileResponse.ContentInfo> getUserContentStats(@PathVariable Long userId) {
        try {
            log.info("管理员查看用户内容统计: userId={}, adminId={}", userId, StpUtil.getLoginIdAsString());
            
            AdminUserProfileResponse.ContentInfo contentInfo = userProfileService.getUserContentInfo(userId);
            
            // 记录管理员查看用户内容统计的操作
            recordAdminActivity("VIEW_USER_CONTENT_STATS", "查看用户内容统计", userId, "user");
            
            return Result.success(contentInfo);
        } catch (Exception e) {
            log.error("获取用户内容统计失败", e);
            return Result.error("获取用户内容统计失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户活动统计
     */
    @GetMapping("/{userId}/activity-stats")
    @SaCheckRole("admin")
    public Result<AdminUserProfileResponse.InteractionInfo> getUserActivityStats(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "30") Integer days) {
        try {
            log.info("管理员查看用户活动统计: userId={}, days={}, adminId={}", 
                    userId, days, StpUtil.getLoginIdAsString());
            
            AdminUserProfileResponse.InteractionInfo activityStats = 
                userProfileService.getUserActivityStats(userId, days);
            
            // 记录管理员查看用户活动统计的操作
            recordAdminActivity("VIEW_USER_ACTIVITY_STATS", "查看用户活动统计", userId, "user");
            
            return Result.success(activityStats);
        } catch (Exception e) {
            log.error("获取用户活动统计失败", e);
            return Result.error("获取用户活动统计失败：" + e.getMessage());
        }
    }

    /**
     * 重新计算用户统计数据
     */
    @PostMapping("/{userId}/recalculate-stats")
    @SaCheckRole("admin")
    public Result<String> recalculateUserStats(@PathVariable Long userId) {
        try {
            log.info("管理员重新计算用户统计: userId={}, adminId={}", userId, StpUtil.getLoginIdAsString());
            userProfileService.recalculateUserStats(userId);
            // 记录管理员重新计算统计数据的操作
            recordAdminActivity("RECALCULATE_USER_STATS", "重新计算用户统计数据", userId, "user");
            return Result.success("重新计算统计数据成功");
        } catch (Exception e) {
            log.error("重新计算用户统计数据失败", e);
            return Result.error("操作失败：" + e.getMessage());
        }
    }

    /**
     * 清理过期活动记录
     */
    @PostMapping("/clean-expired-activities")
    @SaCheckRole("admin")
    public Result<String> cleanExpiredActivities(@RequestParam(defaultValue = "90") Integer days) {
        try {
            log.info("管理员清理过期活动记录: days={}, adminId={}", days, StpUtil.getLoginIdAsString());
            
            Integer cleanedCount = userProfileService.cleanExpiredActivities(days);
            
            // 记录管理员清理活动记录的操作
            recordAdminActivity("CLEAN_EXPIRED_ACTIVITIES", 
                              String.format("清理%d天前的活动记录，共清理%d条", days, cleanedCount), 
                              null, "system");
            
            return Result.success(String.format("成功清理%d条过期活动记录", cleanedCount));
        } catch (Exception e) {
            log.error("清理过期活动记录失败", e);
            return Result.error("操作失败：" + e.getMessage());
        }
    }

    /**
     * 记录管理员操作活动
     */
    private void recordAdminActivity(String activityType, String description, Long targetId, String targetType) {
        try {
            Long adminId = StpUtil.getLoginIdAsLong();
            String ipAddress = getClientIp();
            String userAgent = request.getHeader("User-Agent");
            
            userProfileService.recordUserActivity(adminId, activityType, description, 
                                                 targetId, targetType, ipAddress, userAgent, "SUCCESS");
        } catch (Exception e) {
            log.warn("记录管理员活动失败", e);
        }
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIp() {
        String xip = request.getHeader("X-Real-IP");
        String xfor = request.getHeader("X-Forwarded-For");
        if (xfor != null && !xfor.isEmpty() && !"unknown".equalsIgnoreCase(xfor)) {
            int index = xfor.indexOf(",");
            if (index != -1) {
                return xfor.substring(0, index);
            } else {
                return xfor;
            }
        }
        if (xip != null && !xip.isEmpty() && !"unknown".equalsIgnoreCase(xip)) {
            return xip;
        }
        if (xfor != null && !xfor.isEmpty() && !"unknown".equalsIgnoreCase(xfor)) {
            return xfor;
        }
        return request.getRemoteAddr();
    }
}
